<template>
  <view class="graph-actions">
    <button @tap="handleFilter"><uni-icons type="settings-filled" size="22" /></button>
    <button @tap="handleZoomIn"><uni-icons type="plus" size="22" /></button>
    <button @tap="handleZoomOut"><uni-icons type="minus" size="22" /></button>
    <button @tap="handleRefresh"><uni-icons type="reload" size="22" /></button>
    <button @tap="handleSaveAsImage"><uni-icons type="download" size="22" /></button>
    <button @tap="handleSettings"><uni-icons type="gear-filled" size="22" /></button>
  </view>
</template>

<script>
export default {
  name: 'GraphActions',
  props: {
    chartInstance: {
      type: Object,
      default: null
    },
    chartRef: {
      type: Object,
      default: null
    },
    zoomLevel: {
      type: Number,
      default: 0.8
    }
  },
  emits: ['filter', 'zoom-in', 'zoom-out', 'refresh', 'save-image', 'settings', 'update:zoom-level'],
  methods: {
    handleFilter() {
      this.$emit('filter');
    },
    
    handleZoomIn() {
      console.log('放大操作，chartInstance存在:', !!this.chartInstance);
      
      // 更新缩放级别
      const newZoomLevel = Math.min(this.zoomLevel * 1.2, 3);
      console.log('放大，新的缩放级别:', newZoomLevel);
      
      this.setZoom(newZoomLevel);
      this.$emit('update:zoom-level', newZoomLevel);
      this.$emit('zoom-in', newZoomLevel);
    },
    
    handleZoomOut() {
      console.log('缩小操作，chartInstance存在:', !!this.chartInstance);
      
      // 更新缩放级别
      const newZoomLevel = Math.max(this.zoomLevel / 1.2, 0.3);
      console.log('缩小，新的缩放级别:', newZoomLevel);
      
      this.setZoom(newZoomLevel);
      this.$emit('update:zoom-level', newZoomLevel);
      this.$emit('zoom-out', newZoomLevel);
    },
    
    handleRefresh() {
      this.$emit('refresh');
    },
    
    handleSaveAsImage() {
      this.saveAsImage();
    },
    
    handleSettings() {
      this.$emit('settings');
    },
    
    setZoom(zoomLevel) {
      if (this.chartInstance && typeof this.chartInstance.setOption === 'function') {
        try {
          // 检查图表实例是否有效
          if (this.chartInstance.isDisposed && this.chartInstance.isDisposed()) {
            console.log('图表实例已销毁，无法设置缩放');
            return;
          }

          // 直接更新图表的缩放选项
          this.chartInstance.setOption({
            series: [{
              zoom: zoomLevel,
              center: ['50%', '50%']
            }]
          }, false);
          console.log('缩放设置成功，zoomLevel:', zoomLevel);
        } catch (error) {
          console.error('设置缩放失败:', error);
          // 尝试重新设置整个选项
          try {
            this.chartInstance.setOption(this.chartOption, true);
            console.log('通过重新设置整个选项来更新缩放');
          } catch (e) {
            console.error('重新设置选项也失败:', e);
          }
        }
      } else {
        console.log('图表实例不存在或没有setOption方法，无法设置缩放');
      }
    },
    
    async saveAsImage() {
      this.$emit('save-image');
      
      try {
        // 获取图表组件实例
        const chartComponent = this.chartRef;
        if (!chartComponent) {
          uni.showToast({ title: '图表组件未找到', icon: 'none' });
          return;
        }

        // 显示加载提示
        uni.showLoading({ title: '正在生成图片...' });

        // #ifdef H5
        // H5端直接操作 canvas 元素
        try {
          // 方法1：尝试使用 ECharts 的 getDataURL
          if (this.chartInstance && typeof this.chartInstance.getDataURL === 'function') {
            try {
              const url = this.chartInstance.getDataURL({ 
                type: 'png', 
                pixelRatio: 2, 
                backgroundColor: '#fff' 
              });
              
              if (url && url.startsWith('data:image/')) {
                              // 下载图片 - 仅H5环境
              const a = document.createElement('a');
              a.href = url;
              a.download = 'relation-graph.png';
              a.click();
                
                uni.hideLoading();
                uni.showToast({ title: '图片已保存', icon: 'success' });
                return;
              }
            } catch (echartError) {
                console.warn('ECharts getDataURL 不兼容，使用备用方案');
            }
          }
          
          // 方法2：直接获取 canvas 元素 - 仅H5环境
          // #ifdef H5
          // #ifdef H5
        const canvas = document.querySelector('canvas');
        // #endif
          if (canvas && typeof canvas.toDataURL === 'function') {
            const url = canvas.toDataURL('image/png', 1.0);
            
            // 下载图片 - 仅H5环境
            const a = document.createElement('a');
            a.href = url;
            a.download = 'relation-graph.png';
            a.click();
            
            uni.hideLoading();
            uni.showToast({ title: '图片已保存', icon: 'success' });
            return;
          }
          
          // 方法3：查找lime-echart组件内的canvas
          const chartContainer = chartComponent?.$el;
          if (chartContainer) {
            const canvasInContainer = chartContainer.querySelector('canvas');
            if (canvasInContainer && typeof canvasInContainer.toDataURL === 'function') {
              const url = canvasInContainer.toDataURL('image/png', 1.0);
              
              // 下载图片 - 仅H5环境
              const a = document.createElement('a');
              a.href = url;
              a.download = 'relation-graph.png';
              a.click();
              
              uni.hideLoading();
              uni.showToast({ title: '图片已保存', icon: 'success' });
              return;
            }
          }
          // #endif
          
          throw new Error('无法找到可用的canvas元素');
        } catch (h5Error) {
          console.error('H5端保存图片失败:', h5Error);
          throw h5Error;
        }
        // #endif

        // #ifdef MP || APP-PLUS
        // 小程序和APP端使用 renderToCanvas 方法
        if (chartComponent.renderToCanvas) {
          const canvas = await chartComponent.renderToCanvas();
          if (canvas) {
            // 小程序端保存到相册
            // #ifdef MP
            uni.canvasToTempFilePath({
              canvas: canvas,
              success: (res) => {
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: () => {
                    uni.hideLoading();
                    uni.showToast({ title: '图片已保存到相册', icon: 'success' });
                  },
                  fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({ title: '保存失败', icon: 'error' });
                  }
                });
              },
              fail: (err) => {
                uni.hideLoading();
                uni.showToast({ title: '生成图片失败', icon: 'error' });
              }
            });
            // #endif
            
            // #ifdef APP-PLUS
            // APP端的处理逻辑
            const tempFilePath = await new Promise((resolve, reject) => {
              uni.canvasToTempFilePath({
                canvas: canvas,
                success: (res) => resolve(res.tempFilePath),
                fail: reject
              });
            });
            
            await new Promise((resolve, reject) => {
              uni.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: resolve,
                fail: reject
              });
            });
            
            uni.hideLoading();
            uni.showToast({ title: '图片已保存到相册', icon: 'success' });
            // #endif
          } else {
            throw new Error('Canvas 对象获取失败');
          }
        } else {
          throw new Error('renderToCanvas 方法不存在');
        }
        // #endif

      } catch (error) {
        console.error('保存图片失败:', error);
        uni.hideLoading();
        uni.showToast({ title: '保存图片失败', icon: 'error' });
      }
    }
  }
}
</script>

<style scoped>
.graph-actions {
  position: fixed;
  right: 24px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 18px;
  z-index: 1002;
}

.graph-actions button {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: linear-gradient(135deg, 
    rgba(59,130,246,0.25) 0%, 
    rgba(99,102,241,0.2) 100%);
  border: 1px solid rgba(255,255,255,0.2);
  box-shadow: 
    0 8px 32px rgba(59,130,246,0.25),
    0 4px 16px rgba(0,0,0,0.1),
    inset 0 1px 0 rgba(255,255,255,0.3),
    inset 0 -1px 0 rgba(59,130,246,0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: rgba(255,255,255,0.9);
  backdrop-filter: blur(20px) saturate(180%) brightness(110%);
  -webkit-backdrop-filter: blur(20px) saturate(180%) brightness(110%);
  position: relative;
  overflow: hidden;
}

.graph-actions button::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s;
}

.graph-actions button:hover::before {
  opacity: 1;
}

.graph-actions button:active {
  background: linear-gradient(135deg, 
    rgba(59,130,246,0.35) 0%, 
    rgba(99,102,241,0.3) 100%);
  box-shadow: 
    0 4px 20px rgba(59,130,246,0.3),
    0 2px 8px rgba(0,0,0,0.15),
    inset 0 2px 4px rgba(59,130,246,0.2);
  transform: translateY(1px) scale(0.96);
  border: 1px solid rgba(255,255,255,0.3);
}

.graph-actions button:hover {
  background: linear-gradient(135deg, 
    rgba(59,130,246,0.3) 0%, 
    rgba(99,102,241,0.25) 100%);
  box-shadow: 
    0 12px 40px rgba(59,130,246,0.3),
    0 6px 20px rgba(0,0,0,0.12),
    inset 0 1px 0 rgba(255,255,255,0.4),
    inset 0 -1px 0 rgba(59,130,246,0.15);
  transform: translateY(-2px);
  border: 1px solid rgba(255,255,255,0.25);
}
</style> 